package dao

import (
	"github.com/garyburd/redigo/redis"
	"github.com/go-xorm/xorm"
	"github.com/wonderivan/logger"
	"time"
	"ucenter/app"
)

type Dao struct {
	client      *xorm.Engine
	redisClient *redis.Pool
}

func New(mysqlConf *app.Mysql, redisConf *app.Redis) *Dao {
	var (
		err        error
		retryTimes int
	)
	mysqlEngine, err = xorm.NewEngine("mysql", mysqlConf.DSN)
	mysqlEngine.SetMaxIdleConns(mysqlConf.MaxConnection)
	mysqlEngine.SetMaxOpenConns(mysqlConf.MaxConnection)
	if err != nil {
		logger.Fatal("数据库连接失败:", err)
	}
Retry:
	if err = mysqlEngine.Ping(); err != nil {
		logger.Warn("mysql ping fail, %s", err.Error())
		if retryTimes > 3 {
			time.Sleep(time.Second * 5)
		}
		retryTimes++
		goto Retry
	}
	mysqlEngine.ShowSQL(mysqlConf.Debug)

	redisClient := &redis.Pool{
		MaxIdle:     redisConf.Idle,
		MaxActive:   redisConf.Active,
		IdleTimeout: time.Duration(redisConf.IdleTimeout),
		Dial: func() (redis.Conn, error) {
			conn, err := redis.Dial(redisConf.Network, redisConf.Addr,
				redis.DialConnectTimeout(time.Duration(redisConf.DialTimeout)),
				redis.DialReadTimeout(time.Duration(redisConf.ReadTimeout)),
				redis.DialWriteTimeout(time.Duration(redisConf.WriteTimeout)),
				redis.DialPassword(redisConf.Auth),
				redis.DialDatabase(redisConf.Database),
			)
			if err != nil {
				logger.Error("redis connect fail:", err)
			}
			return conn, nil
		},
	}
	return &Dao{
		client:      mysqlEngine,
		redisClient: redisClient,
	}
}
